<template>
  <el-card class="box-card">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-width="100px" class="demo-ruleForm">

      <el-form-item label="题目归属" prop="type" class="problems-manager-item">
        <el-radio-group v-model="postForm.type" @change="changeType">
          <el-radio label="模拟试卷题库" />
          <el-radio label="练习题库表" />
          <el-radio label="课程" />
        </el-radio-group>
      </el-form-item>
      <br>
      <el-form-item label="考试类型" prop="examType" class="problems-manager-item">
        <el-select v-model="postForm.examType" placeholder="请选择" class="problems-manager-block" @change="querySubjects">
          <el-option
            v-for="(item, index) in examTypes"
            :key="index"
            :label="item"
            :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="postForm.type !== '课程'" label="学科" prop="subjectId" class="problems-manager-item" >
        <el-select v-model="postForm.subjectId" placeholder="请选择" class="problems-manager-block" @change="queryChapter">
          <el-option
            v-for="item in subjects"
            :key="item.subjectId"
            :label="item.subjectName"
            :value="item.subjectId" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="postForm.type === '课程'" label="课程分类" prop="subjectId" class="problems-manager-item" >
        <el-select v-model="postForm.subjectId" placeholder="请选择" class="problems-manager-block" @change="queryChapter">
          <el-option
            v-for="item in courseTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item v-if="postForm.type !== '课程'" label="章节" prop="chapterId" class="problems-manager-item" >
        <el-select v-model="postForm.chapterId" placeholder="请选择" class="problems-manager-block">
          <el-option
            v-for="item in chapters"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="postForm.type === '课程'" label="课程科目" prop="chapterId" class="problems-manager-item" >
        <el-select v-model="postForm.chapterId" placeholder="请选择" class="problems-manager-block">
          <el-option
            v-for="item in courseSubjects"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="题型类别" prop="questType" class="problems-manager-item">
        <el-select v-model="postForm.questType" placeholder="请选择" class="problems-manager-block">
          <el-option
            v-for="item in questTypes"
            :key="item.id"
            :label="item.name"
            :value="item.name" />
        </el-select>
      </el-form-item>

      <el-form-item label="题目标题" class="problems-manager-item">
        <el-input v-model="postForm.title" resize="none" type="textarea"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessTitle"
          class="avatar-uploader"
          name="file">
          <img v-if="postForm.titlePicUrl" :src="version + '/uploadFile/path/' + postForm.titlePicUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="选型A" prop="optiona" class="problems-manager-item">
        <el-input v-model="postForm.optiona" resize="none" type="textarea" @focus="deleteImg('optiona')"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessOptiona"
          class="avatar-uploader"
          name="file">
          <img v-if="images.optiona" :src="version + '/uploadFile/path/' + postForm.optiona" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="选型B" prop="optionb" class="problems-manager-item">
        <el-input v-model="postForm.optionb" resize="none" type="textarea" @focus="deleteImg('optionb')"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessOptionb"
          class="avatar-uploader"
          name="file">
          <img v-if="images.optionb" :src="version + '/uploadFile/path/' + postForm.optionb" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="选型C" prop="optionc" class="problems-manager-item">
        <el-input v-model="postForm.optionc" resize="none" type="textarea" @focus="deleteImg('optionc')"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessOptionc"
          class="avatar-uploader"
          name="file">
          <img v-if="images.optionc" :src="version + '/uploadFile/path/' + postForm.optionc" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="选型D" prop="optiond" class="problems-manager-item">
        <el-input v-model="postForm.optiond" resize="none" type="textarea" @focus="deleteImg('optiond')"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessOptiond"
          class="avatar-uploader"
          name="file">
          <img v-if="images.optiond" :src="version + '/uploadFile/path/' + postForm.optiond" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="选型E" class="problems-manager-item">
        <el-input v-model="postForm.optione" resize="none" type="textarea" @focus="deleteImg('optione')"/>
        <el-upload
          :show-file-list="false"
          :action="version + '/uploadFile'"
          :on-success="uploadSuccessOptione"
          class="avatar-uploader"
          name="file">
          <img v-if="images.optione" :src="version + '/uploadFile/path/' + postForm.optione" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="正确答案" prop="rightAnswerCopy" class="problems-manager-item">
        <el-checkbox-group v-model="postForm.rightAnswerCopy">
          <el-checkbox label="A" name="type" />
          <el-checkbox label="B" name="type" />
          <el-checkbox label="C" name="type" />
          <el-checkbox label="D" name="type"/>
          <el-checkbox label="E" name="type"/>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="答案解析" class="problems-manager-item">
        <el-input v-model="postForm.answerParse" resize="none" type="textarea"/>
      </el-form-item>

      <el-form-item label="考点" class="problems-manager-item">
        <el-input v-model="postForm.testCentre" resize="none" type="textarea"/>
      </el-form-item>
      <el-form-item v-if="postForm.type === '模拟试卷题库'" label="试卷名称" prop="testId" class="problems-manager-item">
        <el-select v-model="postForm.testId" placeholder="请选择" class="problems-manager-block">
          <el-option
            v-for="item in tests"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="postForm.type === '课程'" label="课程名称" prop="courseId" class="problems-manager-item">
        <el-select v-model="postForm.courseId" placeholder="请选择" class="problems-manager-block">
          <el-option
            v-for="item in courses"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button :loading="addLoading" type="primary" @click="submit">提交</el-button>
        <router-link to="/problems-manager"><el-button>取消</el-button></router-link>

      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import axios from 'axios'
import { VERSION } from '@/constants/uri'
import { PROBLEMS_CONTENT } from '@/constants/storage'
import { assignment } from '@/utils/assignment'
const imageSunfix = ['png', 'jpg', 'jpeg']
import { types } from '@/assets/type.js'
export default {
  data() {
    return {
      postForm: {
        id: '',
        examType: '',
        subjectId: '',
        chapterId: '',
        questType: '',
        title: '',
        titlePicUrl: '',
        optiona: '',
        optionb: '',
        optionc: '',
        optiond: '',
        optione: '',
        rightAnswer: '',
        rightAnswerCopy: [],
        answerParse: '',
        testCentre: '',
        type: '',
        testId: '',
        courseId: ''
      },
      images: {
        title: '',
        optiona: '',
        optionb: '',
        optionc: '',
        optiond: '',
        optione: ''
      },
      version: VERSION,
      examTypes: types,
      subjects: [],
      chapters: [],
      questTypes: [],
      courses: [],
      courseTypes: [],
      courseSubjects: [],
      tests: [],
      addLoading: false,
      rules: {
        examType: [
          { required: true, message: '请选择考试类型', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        chapterId: [
          { required: true, message: '请选择章节', trigger: 'change' }
        ],
        questType: [
          { required: true, message: '请选择题目类别', trigger: 'change' }
        ],
        optiona: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        optionb: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        optionc: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        optiond: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        rightAnswer: [
          { required: true, message: '请选择正确答案', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择题目归属', trigger: 'change' }
        ],
        testId: [
          { required: true, message: '请选择试卷名称', trigger: 'change' }
        ],
        courseId: [
          { required: true, message: '请选择试课程名称', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.queryTypes()
    this.queryCourse()
    if (this.$route.params.id) {
      assignment(this.postForm, JSON.parse(sessionStorage.getItem(PROBLEMS_CONTENT)))
      this.postForm.rightAnswerCopy = this.postForm.rightAnswer.split(',')
      this.querySubjects(this.postForm.examType, true)
      this.queryChapter(this.postForm.subjectId, true)
      this.isImage('optiona', this.postForm.optiona)
      this.isImage('optionb', this.postForm.optionb)
      this.isImage('optionc', this.postForm.optionc)
      this.isImage('optiond', this.postForm.optiond)
      this.isImage('optione', this.postForm.optione)
    }
  },
  methods: {
    isImage(key, value) {
      const subfix = value.substr(value.lastIndexOf('.') + 1)
      if (imageSunfix.includes(subfix)) {
        this.images[key] = value
      }
    },
    submit() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.addLoading = true
          this.postForm.rightAnswer = this.postForm.rightAnswerCopy.join(',')
          axios.post('/saveQuest', this.postForm).then(res => {
            this.addLoading = false
            if (res.success) {
              this.$router.push({ path: '/problems-manager' })
            }
          })
        }
      })
    },
    uploadSuccessTitle(res) {
      this.postForm.titlePicUrl = res.fileUploadPath
    },
    uploadSuccessOptiona(res) {
      this.images.optiona = this.postForm.optiona = res.fileUploadPath
    },
    uploadSuccessOptionb(res) {
      this.images.optionb = this.postForm.optionb = res.fileUploadPath
    },
    uploadSuccessOptionc(res) {
      this.images.optionc = this.postForm.optionc = res.fileUploadPath
    },
    uploadSuccessOptiond(res) {
      this.images.optiond = this.postForm.optiond = res.fileUploadPath
    },
    uploadSuccessOptione(res) {
      this.images.optione = this.postForm.optione = res.fileUploadPath
    },
    deleteImg(key) {
      this.images[key] = ''
    },
    querySubjects(examType, isMounted = false) {
      if (!isMounted) {
        this.postForm.subjectId = ''
        this.postForm.chapterId = ''
      }
      return new Promise((resolve) => {
        const uri = this.postForm.type === '课程' ? `/getCourseCategoryListXiaLa/${examType}` : `/getSubjectCategoryListXiaLa/${examType}`
        axios.get(uri).then(res => {
          if (res.success) {
            if (this.postForm.type === '课程') {
              this.courseTypes = res.data
            } else {
              this.subjects = res.data
            }
          }
          resolve()
        })
      })
    },
    queryChapter(subjectId, isMounted = false) {
      if (!isMounted) {
        this.postForm.chapterId = ''
      }
      const uri = this.postForm.type === '课程' ? `/getCourseSubjectListXiaLa/${subjectId}` : `/getSubjectChapterListXiaLa/${subjectId}`
      axios.get(uri).then(res => {
        if (res.success) {
          if (this.postForm.type === '课程') {
            this.courseSubjects = res.data
          } else {
            this.chapters = res.data
          }
        }
      })
    },
    queryTypes() {
      axios.get(`/getQuestTypeListXiaLa`).then(res => {
        if (res.success) {
          this.questTypes = res.data
        }
      })
    },
    queryCourse() {
      axios.get(`/getQuestXiaLa/模拟试卷题库`).then(res => {
        if (res.success) {
          this.tests = res.data
        }
      })
      axios.get(`/getQuestXiaLa/课程`).then(res => {
        if (res.success) {
          this.courses = res.data
        }
      })
    },
    changeType() {
      this.postForm.testId = ''
      this.postForm.examType = ''
      this.postForm.courseId = ''
      this.postForm.subjectId = ''
      this.postForm.chapterId = ''
    }
  }
}
</script>

<style lang="scss">
  $avatar-width: 80px;
  .problems-manager-item {
    display: inline-block;
    width: 45%;
  }

  .problems-manager-item:nth-of-type(2n + 1) {
    margin-right: 9%;
  }

  .problems-manager-block {
    width: 100%;
  }

  .avatar-uploader .el-upload {
    margin-top: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: $avatar-width;
    height: $avatar-width;
    line-height: $avatar-width;
    text-align: center;
  }
  .avatar {
    width: $avatar-width;
    height: $avatar-width;
    display: inline-block;
  }
</style>
